<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 100%;
            height: 300px;
            text-align: center;
            line-height: 300px;
            font-size: 35px;
            color: aliceblue;
        }
        
        div:nth-of-type(odd) {
            background-color: burlywood;
        }
        
        div:nth-of-type(even) {
            background-color: cadetblue;
        }
        
        p {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            line-height: 100px;
            text-align: center;
            position: fixed;
            top: 500px;
            right: 50px;
            background-color: chartreuse;
        }
    </style>
</head>

<body>
    <div>这是div1</div>
    <div>这是div2</div>
    <div>这是div3</div>
    <div>这是div4</div>
    <div>这是div5</div>
    <div>这是div6</div>
    <div>这是div7</div>
    <div>这是div8</div>
    <div>这是div9</div>
    <div>这是div10</div>
    <div>这是div11</div>
    <div>这是div12</div>
    <div>这是div13</div>
    <div>这是div14</div>
    <p>回到顶部</p>
    <script>
        let pp = document.querySelector('p')
        console.log(pp);
        window.addEventListener('scroll', function() {
            if (scrollY >= 300) {
                pp.style.display = 'block'
            } else {
                pp.style.display = 'none'
            }
        })


        let timeId = null
        pp.addEventListener('click', function() {
            // window.scrollTo(0, 0)
            timeId = setInterval(function() {

                window.scrollTo(0, scrollY - 40)
                if (scrollY <= 0) {
                    clearInterval(timeId)
                }
            }, 50)
        })
    </script>
</body>

</html>